package study.netty.websocket.support.server;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.concurrent.GlobalEventExecutor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ChatHandler extends SimpleChannelInboundHandler<BinaryWebSocketFrame> {

	//用于记录和管理所有客户端的channle
	private static ChannelGroup clients = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

	/**
	 * 当客户端连接服务端之后（打开连接）
	 */
	@Override
	public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
		log.info("客户连接，channel对应的长id为：" + ctx.channel());
		clients.add(ctx.channel());
	}

	/**
	 * 当客户端连与接服务端断开之后（断开连接）
	 */
	@Override
	public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
		//当触发handlerRemoved,ChannelGroup会自动移除客户端的channel
		log.info("客户端断开，channel对应的长id为：" + ctx.channel());
		clients.remove(ctx.channel());
	}

	/**
	 * 用户行为触发
	 */
	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
		System.err.println("userEventTriggered  state = " + evt.toString());
		// TODO Auto-generated method stub
		if (evt instanceof IdleStateEvent) {
			IdleStateEvent stateEvent = (IdleStateEvent) evt;
			System.err.println(stateEvent.state());
			// 读空闲（服务器端）
			if (IdleState.READER_IDLE == stateEvent.state()) {
				// 30秒未读取到信息，关闭连接
				ctx.channel().close();
				ctx.close();
			}
		}
	}

	/**
	 * 异常
	 */
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
			throws Exception {
		System.err.println("exceptionCaught");
		System.err.println(cause.getMessage());
		ctx.channel().close();
		ctx.close();
	}

	@Override
	protected void channelRead0(ChannelHandlerContext ctx,
								BinaryWebSocketFrame msg) throws Exception {
		// TODO Auto-generated method stub
		// 获取客户端传输过来的信息，解析
//		RequestInfo.MessageWebsocketRequest request = CustomProtobufDecoder
//				.decode(msg.content());
//		if (request == null) {
//			RequestInfo.MessageWebsocketResponse response = RequestInfo.MessageWebsocketResponse
//					.newBuilder().setCode(RequestInfo.HttpResultEnum.fail)
//					.setMessage("数据解析异常").build();
//			ctx.channel().writeAndFlush(new BinaryWebSocketFrame(CustomProtobufEncoder.encode(response)));
//			System.err.println("request == null 数据解析异常");
//			return;
//		}
		/*
		
		
		//校验权限
		Boolean authority = validAuthority(request);
		//无权限
		if(!authority){
			RequestInfo.MessageWebsocketResponse.Builder responseBuild = RequestInfo.MessageWebsocketResponse.newBuilder();
			responseBuild.setCode(RequestInfo.HttpResultEnum.account_not_authority);
			responseBuild.setRequestId(request.getRequestId());
			RequestInfo.MessageWebsocketResponse respnse = responseBuild.build();
			ctx.channel().writeAndFlush(new BinaryWebSocketFrame(CustomProtobufEncoder.encode(respnse)));
			System.err.println("sign校验失败:requestId = "+request.getRequestId());
			return;
		}
		 * /
		 */
		//心跳类型放行
//		if (request.getAction().getNumber() != RequestInfo.ActionEnum.tickTime_VALUE) {
//			taskHandle(request, ctx);
//		} else {//心跳返回，客户端测试是否粘包
//			ByteBuf content = msg.content();
//			ByteBuf r = Unpooled.buffer(content.capacity());
//			r.writeBytes(content);
//			ctx.channel().writeAndFlush(new BinaryWebSocketFrame(r));
//		}


	}
	// @Override
	// protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame
	// msg)
	// throws Exception {
	// // TODO Auto-generated method stub
	// //获取客户端传输过来的信息
	// System.err.println(msg.getClass());
	// System.err.println(msg.content());
	// Channel channel = ctx.channel();
	// //当有用户发送消息的时候，对其他的用户发送消息
	// for (Channel ch : clients) {
	// if (ch == channel) {
	// RequestInfo.MessageWebsocketResponse s =
	// RequestInfo.MessageWebsocketResponse.newBuilder().setRequestId("111112222").build();
	// ch.writeAndFlush(s);
	// ch.writeAndFlush(new TextWebSocketFrame("11111111"));
	// }
	// }
	// System.out.println("[" + channel.remoteAddress() + "]: " + msg + "\n");
	//
	// }

}
